/**
 * 
 */
package com.alstudio.core.mission;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import org.apache.http.Header;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.recharge.ComintChargeOrderHttpResultWrap;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppEventType;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.utils.activity.ALActivityManager;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.mission.ALMissionHttpManager;
import com.alstudio.utils.mission.ALMissionHttpManager.MissionInfoCallback;
import com.alstudio.utils.mission.MissionInfo;
import com.alstudio.view.ViewUtils;
import com.alstudio.view.popwindow.ALPopWindowUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loovee.imaohu.R;

/**
 * @author alonso lee
 * 
 */
public class ALMissionManager implements MissionInfoCallback, OnDismissListener {

	private static ALMissionManager instance;

	private ALMissionHttpManager mAlMissionHttpManager;
	private boolean isMissionAllCompleteNoticed = false;
	private MissionInfo unDoMission = null;
	private int unDoMissionIndex = -1;

	private final String MISSION_COMPLETED_KEY = "mission_completed";

	private PopupWindow mPopWindow;

	private View icon_close, reward_layout, progress_layout;

	private TextView title, task_desc, reward, btn, progress_txt;
	private ProgressBar progressBar1;

	private ArrayList<MissionInfo> tasks = new ArrayList<MissionInfo>();

	/**
	 * 获取任务管理器实例
	 * 
	 * @return
	 */
	public static ALMissionManager getDefaultMissionManager() {
		if (instance == null) {
			instance = new ALMissionManager();
		}
		return instance;
	}

	/**
	 * 
	 */
	public ALMissionManager() {
		mAlMissionHttpManager = new ALMissionHttpManager();
		mAlMissionHttpManager.setMissionCallback(this);
		initPopWindow();
	}

	/**
	 * @return the unDoMission
	 */
	public MissionInfo getUnDoMission() {
		return unDoMission;
	}

	public void checkMission() {

		mAlMissionHttpManager.checkTaskList(ALLocalEnv.getLocalEnv()
				.getVersionConfig().getMissionUrl()
				+ "/task/main");
	}

	/*********************************** popwindow管理 ***********************************************/
	public void showMissionPopWindow(View parent) {
		// ALPopWindowUtils.showPopWindow(mPopWindow, parent);
		mPopWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
		ALActivityManager.getALActivityManager().getCurrentActivity()
				.enterBlur();

		if (isMissionAllCompleteNoticed) {
			title.setText(R.string.TxtDailyTask);
			task_desc.setText(R.string.TxtDailyTaskComplete);
			ViewUtils.goneView(progress_layout);
			ViewUtils.goneView(reward_layout);
			btn.setEnabled(false);
		} else {
			btn.setEnabled(false);
			String t = ALLocalEnv.getLocalEnv()
					.getString(R.string.TxtDailyTask);
			t += "(" + (unDoMissionIndex + 1) + "/" + tasks.size() + ")";
			title.setText(t);

			progress_txt.setText((unDoMissionIndex + 1) + "/" + tasks.size());

			task_desc.setText(unDoMission.getDesc());

			String r = "";
			if (!TextUtils.isEmpty(unDoMission.getAddgold())) {
				// 奖励金币
				r = ALLocalEnv.getLocalEnv().getString(R.string.TxtTaskGold);
				r = String.format(r, unDoMission.getAddgold());
			} else if (!TextUtils.isEmpty(unDoMission.getAddexp())) {
				// 奖励经验
				r = ALLocalEnv.getLocalEnv().getString(R.string.TxtTaskExp);
				r = String.format(r, unDoMission.getAddexp());
			}

			reward.setText(r);
			progressBar1.setProgress(((unDoMissionIndex + 1) * 100)
					/ tasks.size());
			ViewUtils.showView(progress_layout);
			ViewUtils.showView(reward_layout);
			if ("1".equals(unDoMission.getStatus())) {
				// 可领取
				btn.setText(R.string.TxtTaskGetGold);
				btn.setEnabled(true);
			} else {
				// 未完成
				btn.setText(R.string.TxtTaskUnDo);
			}
		}

	}

	private void initPopWindow() {
		View view = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.task_window, null);

		title = (TextView) view.findViewById(R.id.title);
		task_desc = (TextView) view.findViewById(R.id.task_desc);
		reward = (TextView) view.findViewById(R.id.reward);
		btn = (TextView) view.findViewById(R.id.btn);
		progress_txt = (TextView) view.findViewById(R.id.progress_txt);

		btn.setOnClickListener(btnClickListener);

		progressBar1 = (ProgressBar) view.findViewById(R.id.progressBar1);

		reward_layout = view.findViewById(R.id.reward_layout);
		progress_layout = view.findViewById(R.id.progress_layout);

		icon_close = view.findViewById(R.id.icon_close);

		icon_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mPopWindow.dismiss();
			}
		});

		mPopWindow = ALPopWindowUtils.createPopupWindowWithView(
				ALLocalEnv.getLocalEnv(), view);

		mPopWindow.setOnDismissListener(this);
	}

	@Override
	public void onDismiss() {
		// TODO Auto-generated method stub
		ALActivityManager.getALActivityManager().getCurrentActivity()
				.exitBlur();
	}

	private OnClickListener btnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (unDoMission != null) {
				if (!TextUtils.isEmpty(unDoMission.getStatus())) {
					if ("1".equals(unDoMission.getStatus())) {
						mPopWindow.dismiss();
						onGetTaskReward(unDoMission.getTask_id(), ALLocalEnv
								.getLocalEnv().getVersionConfig()
								.getServerInfo().getTaskJava());
					}
				}
			}
		}
	};

	/*************************************** 任务解析 **************************************/

	private void checkMissionCompleteLable() {
		isMissionAllCompleteNoticed = ALLocalEnv.getLocalEnv().getSpManager()
				.getBoolean(MISSION_COMPLETED_KEY, true);
	}

	private void updateMissionCompletedLable(boolean isCompleted) {
		ALLocalEnv.getLocalEnv().getSpManager()
				.putBoolean(MISSION_COMPLETED_KEY, isCompleted);
	}

	private void parseTask(ArrayList<MissionInfo> tasks, int code) {
		if (tasks == null || tasks.size() == 0) {
			ALLog.d("任务列表为空");
			return;
		}
		this.tasks.clear();
		this.tasks.addAll(tasks);

		unDoMission = null;

		if (code == 200) {
			boolean isAllDone = true;
			unDoMissionIndex = -1;
			for (int i = 0; i < tasks.size(); i++) {
				unDoMission = tasks.get(i);
				if (ALNumericUtils.parseInt(unDoMission.getStatus(), 0) != 3) {
					isAllDone = false;
					unDoMissionIndex = i;
					break;
				}
			}
			if (isAllDone) {
				// 所有都完成了
				ALLog.d("所有任务都完成了");

				checkMissionCompleteLable();
				updateMissionCompletedLable(true);
				if (isMissionAllCompleteNoticed) {
					// 通知ui
					ALXmppEventType eventType = ALXmppEventType.XMPP_MISSION_COMPLETED_EVENT;
					ALXmppEvent tmp = new ALXmppEvent(eventType);
					ALLocalEnv.mXmppEventNotifyManager.notifyAllListener(tmp);
				}

			} else {
				updateMissionCompletedLable(false);
				ALLog.d("第 " + unDoMissionIndex + " 任务未完成 "
						+ unDoMission.getDesc());
				ALXmppEventType eventType = ALXmppEventType.XMPP_NEW_MISSION_ALERT_EVENT;
				ALXmppEvent tmp = new ALXmppEvent(eventType);
				tmp.setData(unDoMission);
				tmp.setIntData(unDoMissionIndex);
				ALLocalEnv.mXmppEventNotifyManager.notifyAllListener(tmp);
			}

		} else {
			ALLog.e("解析任务出错错误码为 " + code);
		}
	}

	@Override
	public void onGetTaskList(ArrayList<MissionInfo> tasks, int code,
			int dailyComplete) {
		// TODO Auto-generated method stub
		parseTask(tasks, code);
	}

	@Override
	public void onConnectFail() {
		// TODO Auto-generated method stub
		ALLog.e("任务连接出错");
	}

	/*********************************************** 完成任务 *********************************************************/

	public void onShareTaskFinish(String channel, String taskId, String url) {
		NormalTaskRequestData data = new NormalTaskRequestData();
		data.setUsername(ALLocalEnv.getLocalEnv().getMyAccount().getUserName());
		data.setTaskId(taskId);
		data.setChannel(channel);

		onShareTaskFinish(data, ALLocalEnv.getLocalEnv().getDefaultWebHeads(),
				url);
	}

	public void onShareTaskFinish(NormalTaskRequestData data,
			HashMap<String, String> headers, String url) {

		if (data == null) {
			return;
		}

		if (TextUtils.isEmpty(url)) {
			return;
		}

		AsyncHttpClient client = new AsyncHttpClient();
		client.addHeader("keepAlive", "false");
		client.addHeader("content-type", "application/octet-stream");
		client.addHeader("Connection", "close");

		if (headers != null && headers.size() > 0) {

			Set<String> keySet = headers.keySet();

			for (String s : keySet) {
				client.addHeader(s, headers.get(s));
			}
		}

		try {
			String params = String.format("?username=%s&taskid=%s&channel=%s",
					URLEncoder.encode(data.getUsername(), "UTF-8"),
					URLEncoder.encode(data.getTaskId(), "UTF-8"),
					URLEncoder.encode(data.getChannel(), "UTF-8"));

			if (TextUtils.isEmpty(url)) {
				url = ALLocalEnv.getLocalEnv().getVersionConfig().getTaskJava();
			}

			if (!url.contains("/share.action")) {
				url += "/share.action";
			}

			url += params;

			ALLog.d("任务完成url " + url);

			client.post(url, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					// TODO Auto-generated method stub
					ALLog.d("提交成功");

					if (headers != null) {
						ComintChargeOrderHttpResultWrap result = new ComintChargeOrderHttpResultWrap();
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
					}

				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					// TODO Auto-generated method stub
					ALLog.d("提交失败" + statusCode + " responseBody "
							+ new String(responseBody));
					if (headers != null) {
						for (Header h : headers) {
							ALLog.d("名字 " + h.getName() + " 值 " + h.getValue());
						}
					}

				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*********************************************** 领取奖励 ******************************************************/

	public void onGetTaskReward(String taskId, String url) {
		NormalTaskRequestData data = new NormalTaskRequestData();
		data.setUsername(ALLocalEnv.getLocalEnv().getMyAccount().getUserName());
		data.setTaskId(taskId);

		onGetTaskReward(data, ALLocalEnv.getLocalEnv().getDefaultWebHeads(),
				url);
	}

	public void onGetTaskReward(NormalTaskRequestData data,
			HashMap<String, String> headers, String url) {

		if (data == null) {
			return;
		}

		if (TextUtils.isEmpty(url)) {
			return;
		}

		AsyncHttpClient client = new AsyncHttpClient();
		client.addHeader("keepAlive", "false");
		client.addHeader("content-type", "application/octet-stream");
		client.addHeader("Connection", "close");

		if (headers != null && headers.size() > 0) {

			Set<String> keySet = headers.keySet();

			for (String s : keySet) {
				client.addHeader(s, headers.get(s));
			}
		}

		try {
			String params = String.format("?username=%s&taskid=%s",
					URLEncoder.encode(data.getUsername(), "UTF-8"),
					URLEncoder.encode(data.getTaskId(), "UTF-8"));

			if (TextUtils.isEmpty(url)) {
				url = ALLocalEnv.getLocalEnv().getVersionConfig().getTaskJava();
			}

			if (!url.contains("/reward.action")) {
				url += "/reward.action";
			}

			url += params;

			ALLog.d("领取任务奖励url " + url);

			client.post(url, new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int statusCode, Header[] headers,
						byte[] responseBody) {
					// TODO Auto-generated method stub
					ALLog.d("提交成功刷新任务状态");
					checkMission();
				}

				@Override
				public void onFailure(int statusCode, Header[] headers,
						byte[] responseBody, Throwable error) {
					// TODO Auto-generated method stub
					ALLog.d("提交失败" + statusCode + " responseBody "
							+ new String(responseBody));

				}
			});
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public class NormalTaskRequestData {
		private String username;
		private String taskId;
		private String channel;

		/**
		 * @return the username
		 */
		public String getUsername() {
			return username;
		}

		/**
		 * @param username
		 *            the username to set
		 */
		public void setUsername(String username) {
			this.username = username;
		}

		/**
		 * @return the taskId
		 */
		public String getTaskId() {
			return taskId;
		}

		/**
		 * @param taskId
		 *            the taskId to set
		 */
		public void setTaskId(String taskId) {
			this.taskId = taskId;
		}

		/**
		 * @return the channel
		 */
		public String getChannel() {
			return channel;
		}

		/**
		 * @param channel
		 *            the channel to set
		 */
		public void setChannel(String channel) {
			this.channel = channel;
		}

	}

}
